#!/usr/bin/python3.8
# -*- coding:UTF-8 -*-
"""
@author:    lizhiheng
@date:      2022/2/9
@software:  PyCharm
@file:      logging_debug.py
@project:   tender_project
@time:      10:18
@user:      Administrator
"""
import logging
import os.path
import time
import colorlog

class MyLogging:
    """
    使用方法:直接调用,生成所对应的实例 调用self.logging去实现debug info 等功能
    """
    def __init__(self, project_name,debug_level,write_level):
        self.debug_level = debug_level
        self.write_level = write_level
        self.project_name = project_name
        self.logging = logging
        self.log_path = os.path.join(os.path.dirname(os.getcwd()), "logs")
        self.logger = self.logging.getLogger()
        self.logger.setLevel(self.debug_level)
        self.log_colors_config = {
            'DEBUG': 'cyan',  # cyan white
            'INFO': 'green',
            'WARNING': 'yellow',
            'ERROR': 'red',
            'CRITICAL': 'bold_red',
        }
        self.logging_formatter = self.logging.Formatter("%(asctime)s - %(filename)s  - %(funcName)s - [%(lineno)d] - %(levelname)s : %(message)s")
        self.formatter = colorlog.ColoredFormatter("%(log_color)s%(asctime)s - %(filename)s - %(funcName)s - [line:%(lineno)d] [%(levelname)s] : %(message)s",
                                                   datefmt='%Y-%m-%d  %H:%M:%S',
                                                   log_colors=self.log_colors_config
                                                   )  # 定义handler的输出格式
        self.debug_log()
        # self.write_log()

    def write_log(self):
        if not os.path.exists(self.log_path):
            os.makedirs(self.log_path)
        rq = time.strftime('%Y_%m_%d', time.localtime(time.time()))
        log_name = os.path.join(self.log_path, self.project_name + "_" + rq + ".logs")
        fh = self.logging.FileHandler(log_name, mode="a", encoding="utf-8")
        fh.setFormatter(self.logging_formatter)
        fh.setLevel(self.write_level)
        self.logger.addHandler(fh)

    def debug_log(self):
        """
        输出log日志
        """
        ch = self.logging.StreamHandler()  # 创建一个流handler
        ch.setLevel(self.debug_level)  # 设置日志输出级别
        ch.setFormatter(self.formatter)  # 设置handler的输出格式
        self.logger.addHandler(ch)  # 将logger添加到handler里面


if __name__ == '__main__':
    m = MyLogging("lzh",debug_level=logging.DEBUG,write_level=logging.INFO)
    m.logging.debug("楼主1")  # 输出信息，打印全部的日志,详细的信息,通常只出现在诊断问题上
    m.logging.info("楼主2")  # 信息   打印info,warning,error,critical级别的日志,确认一切按预期运行
    m.logging.warning("lzh1")  # 警告信息 打印warning,error,critical级别的日志,一个迹象表明,一些意想不到的事情发生了,或表明一些问题在不久的将来(例如。磁盘空间低”),这个软件还能按预期工作
    m.logging.error("lzh2")  # 错误信息  打印error,critical级别的日志,更严重的问题,软件没能执行一些功能
    m.logging.critical("lzh3")  # 危急信息 打印critical级别,一个严重的错误,这表明程序本身可能无法继续运行
    m.logging.debug("如果设置了日志级别为NOTSET,那么这里可以采取debug、info的级别的内容也可以显示在控制台上了")